import React, {
    Component,
} from 'react';
import { connect } from 'react-redux';
import {
    AppState,
    Alert,
    View,
    DeviceEventEmitter,
    Text,
    ScrollView,
    FlatList
} from 'react-native';

import {CachedImage} from "react-native-img-cache";
import SplashScreen from 'react-native-splash-screen';

import Banner from '../../components/banner';
import TabHeader from '../../components/tabheader';
import CXIcon from "../../components/cxicon/CXIcon";

import { skill, my } from '../../actions/match';
import { finish_userinfo, cfg } from '../../actions/check';
import { getBanner } from '../../actions/banner';
import { SETUSERINFO, logout } from '../../actions/reglogin';
import { getItem } from '../../actions/storage';

import storage from '../../config/storage.json';

import styles from "./css/chat";

class ChatTab extends Component {

    static navigationOptions = ({ navigation }) => {
        return {
            title: '勾搭',
            tabBarIcon: ({focused, tintColor})=>(
                <CXIcon name="mainpage_tab" size={31} color={tintColor} />
            ),
        };
    }

    constructor(props){
        super(props);
        this.state = {
            myRelateve_list : [],
            hot_list: [],
            recom_list: [],
            logout_flg: false
        };
    }

    componentWillMount(){
        //监听下线消息
        DeviceEventEmitter.addListener('onLogout', () => {
            if(this.state.logout_flg == false){
                logout();
                this.props.dispatch({
                    type: SETUSERINFO,
                    uid: 0,
                    token: "",
                    avatar: "",
                    nick: "",
                    sex: 0
                });
                if(AppState.currentState == 'active'){
                    Alert.alert(
                        "", 
                        "你的账号已在其他设备登录，请注意账号信息安全",
                        [
                            {text: '确定', onPress: () => this.props.navigation.navigate('Reglogin', {transition: 'pop'})},
                        ],
                        { cancelable: false}
                    );
                }else{
                    AppState.addEventListener('change', (nextAppState) => {
                        if(nextAppState == 'active'){
                            Alert.alert(
                                "", 
                                "你的账号已在其他设备登录，请注意账号信息安全",
                                [
                                    {text: '确定', onPress: () => {
                                        AppState.removeEventListener('change');
                                        this.props.navigation.navigate('Reglogin', {transition: 'pop'});
                                    }},
                                ],
                                { cancelable: false}
                            );
                        }
                    });
                }
                this.state.logout_flg = true;
            }
        });

        getItem([
            storage.userinfo.sex,
            storage.userinfo.avatar,
            storage.userinfo.nickname
        ]).then((result) => {
            let uid = global.uid;
            let token = global.token;
            if (uid > 0 && token != "") {
              let sex = result[0][1];
              let avatar = result[1][1];
              let nickname = result[2][1];
              this.props.dispatch({
                type: SETUSERINFO,
                uid,
                token,
                avatar,
                nick: nickname,
                sex
              });
            }
        })
    }

    componentDidMount(){
        //获取banner
        getBanner(this.props.dispatch);
        // //与我有关
        my(list => this.setState({myRelateve_list: list}));
        //推荐用户列表
        skill(0, 1, list => this.setState({recom_list: list}))
        //检测是否已经填写完成资料
        finish_userinfo(this);
        //获取大礼物相关配置
        cfg(this.props.dispatch);
        SplashScreen.hide();
    }

    componentWillUnmount() {
        AppState.removeEventListener('change');
    }

    render() {
        return (
            <View style={styles.container}>
                <TabHeader title="快撩" left={
                    <CXIcon name='winner' size={20}></CXIcon>
                }>
                </TabHeader>
                <ScrollView>
                    <View style={styles.bannerBox}>
                        <Banner list={this.props.banner} />
                    </View>
                    <View style={styles.RelativeBox}>
                        <View style={styles.boxHeader}><Text style={styles.boxHeaderTitle}>和我相关</Text></View>
                        <FlatList
                            keyExtractor={(item, index) => "relative_" + item.uid} 
                            data={this.state.myRelateve_list}
                            horizontal={true}
                            contentContainerStyle={styles.RelativeContentContainer}
                            showsHorizontalScrollIndicator={false}
                            initialNumToRender={4}
                            renderItem={({item}) => 
                            <View key={item.uid} style={styles.relativeItem}>
                                <CachedImage 
                                    resizeMode="contain" 
                                    source={{uri: item.appface}} 
                                    defaultSource={require('./imgs/default_dynamic_bg.png')}
                                    style={styles.relativeAvatar} />
                                <View style={styles.relativeUserInfo}>
                                    <Text style={styles.relativeNick}>{item.nickname.substr(0, 4)+(item.nickname.length>4?"...":"")}</Text>
                                    <Text style={styles.relativeAge}>{item.age}</Text>
                                </View>
                                <Text style={styles.relativeLevel}>{item.intro}</Text>
                            </View>
                            }
                        />
                    </View>
                    <View style={styles.RecomBox}>
                        <View style={styles.boxHeader}><Text style={styles.boxHeaderTitle}>推荐学妹</Text></View>
                        <FlatList
                            keyExtractor={(item, index) => "recom_" + item.uid} 
                            data={this.state.recom_list}
                            contentContainerStyle={styles.RecomContentContainer}
                            initialNumToRender={4}
                            renderItem={({item}) => 
                            <View key={item.uid} style={styles.RecomRow}>
                                <CachedImage 
                                    resizeMode="contain" 
                                    source={{uri: item.appface}} 
                                    defaultSource={require('./imgs/default_dynamic_bg.png')}
                                    style={styles.RecomAvatar} />
                                <View style={styles.RecomBody}>
                                    <Text style={styles.RecomNick}>{item.nickname}</Text>
                                    <Text style={styles.RecomExtroInfo}>{item.location + "*" + item.trade.name}</Text>
                                    <View style={styles.RecomSkillList}>
                                {item.skills.map((item, i) => {
                                    return (
                                        <Text key={item.sid} style={styles.RecomItemSkill}>{item.girl_name}</Text>
                                    )
                                })}
                                    </View>
                                </View>
                            </View>
                            }
                        />
                    </View>
                </ScrollView>
            </View>
        )
    }
}

function mapStateToProps(state) {
  return {
    banner: state.banner.home_banner
  }
}

export default connect(mapStateToProps)(ChatTab);